import React, {useEffect, useState} from "react";
import {Text} from "react-native-elements";
import {
    Animated,
    Dimensions,
    ImageBackground,
    ScrollView,
    StyleSheet,
    TextInput,
    TouchableHighlight,
    TouchableOpacity,
    View
} from "react-native";
import pool_find from "../assets/Pool/pool_find.png";
import {fontSize_12, fontSize_15, fontSize_16} from "./theme";
import {SvgXml} from "react-native-svg";
import {addSvgXml, rightSvgXml, subSvgXml} from "../libs/svgXml";
import {Avatar} from "react-native-elements/dist/avatar/Avatar";
import {
    addTokenToChain,
    getTokenListByChainID,
    nowWallet,
    removeTokenFromChain,
    tokenNetType
} from "./smartxL2Libs/L2_Data";
import {useFocusEffect} from "@react-navigation/native";

const {width,height,scale} = Dimensions.get("window");

const L2_GetToken = ({navigation,route}:any) => {
    const [searchText,setSearchText] = useState("")
    const [chainID,setChainID] = useState(route?.params?.chainID)
    const [hotToken,setHotToken] = useState([
        {
            chainID:"",
            tokenName:"",
            tokenSymbolName:"",
            tokenAddress:"",
            tokenImg:"",
        }
    ])
    const [selectedHotToken,setSelectedHotToken]= useState([])
    useEffect(()=>{
        initHotToken();
        return ()=> {
        }
    },[])
    useFocusEffect(
        React.useCallback(() => {
            initHotToken()
            return ()=> {
            };
        }, [])
    );
    const initHotToken = async () => {
        let res = await getTokenListByChainID(nowWallet.chainID,nowWallet.address);
        console.log(res.tokenAddressList)
        setSelectedHotToken(res.tokenAddressList);
        const hotTokenTemp = [];
        let hotTokenRes = [];
        for(let i = 0 ; i < hotTokenTemp.length;i++)
        {
            if(hotTokenTemp[i].chainID === chainID)
            {
                hotTokenRes.push(hotTokenTemp[i])
            }
        }
        setHotToken(hotTokenRes)
    }

    const updateTokenSelect = async (item:any) => {
        let token:tokenNetType = {
            chainID:nowWallet.chainID,
            tokenSymbloName:item.tokenSymbolName,
            tokenName:item.tokenName,
            tokenAddress:item.tokenAddress,
            tokenPrice_CNY:"0",
            tokenPrice_USDT:"0",
            tokenImg:item.tokenImg,
            balance:"0",
            walletAddress:nowWallet.address
        }
        try {
            let index = selectedHotToken.findIndex(address => {
                return address === item.tokenAddress
            });
            let index_hotToken = hotToken.findIndex(itemTemp => {
                return itemTemp.tokenAddress === item.tokenAddress
            });
            console.log(index)
            let selectedHotTokenTemp = [...selectedHotToken];
            let hotTokenTemp = [...hotToken];
            if (index > -1) {
                await removeTokenFromChain(nowWallet.chainID,token.tokenAddress,nowWallet.address)
                selectedHotTokenTemp.splice(index, 1);
                setSelectedHotToken(selectedHotTokenTemp);
                setHotToken(hotTokenTemp)
                return;
            }
            await addTokenToChain(nowWallet.chainID,token,nowWallet.address)
            selectedHotTokenTemp.push(item.tokenAddress);
            setSelectedHotToken(selectedHotTokenTemp);
            setHotToken(hotTokenTemp)
            return;
        }
        finally {
            console.log(hotToken)
        }
    }

    const checkIsSelected = (tokenAddress:string) => {
        let index = selectedHotToken.indexOf(tokenAddress);
        if(index>-1)
        {
            return true
        }
        return false
    }

    return (
        <View style={styles.container}>
            <View style={{flexDirection:"row",justifyContent:"space-between",alignItems:"center",marginBottom:5}}>
                <View style={{justifyContent:"center",height:30,flex:1,flexDirection:"row",backgroundColor:"#f5f6f8",borderRadius:20,marginTop:10}}>
                    <ImageBackground
                        source={pool_find}
                        style={{ width: 15, height:15, marginLeft:10,paddingRight:25,alignSelf:'center' }} />
                    <TextInput
                        underlineColorAndroid={'transparent'}
                        placeholder= {"搜索代币名称/合约/项目名称"}
                        onChangeText={
                            (value) => {
                                setSearchText(value)
                                console.log(searchText)
                            }
                        }
                        style={{
                            flex:1,
                            padding:0,
                            paddingRight:20,
                            fontSize:fontSize_15
                        }
                        }
                    />
                </View>
                <TouchableOpacity
                    style={{height:30,marginTop:10,width:50,alignItems:"center",justifyContent:"flex-end",flexDirection:"row"}}
                    activeOpacity={1} onPress={()=>{
                    navigation.goBack();
                }}>
                    <Text style={{fontSize:fontSize_15,textAlignVertical:"center",textAlign:"center"}}>{"取消"}</Text>
                </TouchableOpacity>
                {/*<Text style={{marginLeft:"2%",alignSelf:"center",fontWeight:"bold"}}>取消</Text>*/}
            </View>
            <TouchableHighlight underlayColor={"transparent"} onPress={()=>{
                navigation.navigate("L2_HomeAssetView")
            }} >
                <View style={styles.pageView}>
                    <View style={{flex:1,height:55,marginLeft:10,alignItems:"center",flexDirection:"row",borderBottomColor:"#f5f5f5",borderBottomWidth:1}}>
                        <Text style={{flex:1,fontSize:fontSize_16}}>首页资产</Text>
                        <SvgXml xml={rightSvgXml()} width={25} height={25}/>
                    </View>
                </View>
            </TouchableHighlight>
            <TouchableHighlight underlayColor={"transparent"} onPress={()=>{
                navigation.navigate("L2_CustomToken")
            }} >
                <View style={styles.pageView}>
                    <View style={{flex:1,height:55,marginLeft:10,alignItems:"center",flexDirection:"row",borderBottomColor:"#f5f5f5",borderBottomWidth:1}}>
                        <Text style={{flex:1,fontSize:fontSize_16}}>自定义代币</Text>
                        <SvgXml xml={rightSvgXml()} width={25} height={25}/>
                    </View>
                </View>
            </TouchableHighlight>
            <View style={styles.divider_10}/>
            <Text style={styles.listTitle}>热门代币</Text>
            <ScrollView style={{width:"100%"}} showsVerticalScrollIndicator={false}>
            {
                hotToken.length?
                    hotToken.map((item,index)=>(
                        <View style={styles.tokenInfoContainer} key={"hotToken_"+index}>
                            <Avatar source={{uri:item.tokenImg}} size={37} rounded={true}/>
                            <View style={styles.tokenMsgContainer}>
                                <View style={styles.tokenInfoView}>
                                    <Text style={styles.tokenName}>{item.tokenName}</Text>
                                    <Text style={styles.tokenAddress}>{item.tokenAddress.slice(0,8)}...{item.tokenAddress.slice(-8)}</Text>
                                </View>
                                <View style={{padding:0,borderWidth:2/scale,borderColor:checkIsSelected(item.tokenAddress)?"#c6c6c6":"#417ed4",borderRadius:99}}>
                                    <SvgXml xml={checkIsSelected(item.tokenAddress)?subSvgXml("#c6c6c6"):addSvgXml("#417ed4")} width={22} height={22} onPress={()=>{
                                        updateTokenSelect(item);
                                    }}/>
                                </View>
                            </View>
                        </View>
                    )):null
            }
            </ScrollView>
        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        width: width,
        alignItems: "center",
        flexDirection: "column",
        paddingLeft: 20,
        paddingRight: 20,
        backgroundColor: "white"
    },
    pageView:{
        width:width,
        height:55,
        backgroundColor:"white",
        flexDirection:"row",
        alignItems:"center",
        paddingLeft:10,
        paddingRight:10,
    },
    divider_10:{
        width:width,
        height:10,
        backgroundColor:"#f6f6f6"
    },
    listTitle:{
        fontSize:fontSize_16,
        width:"100%",
        lineHeight:40
    },
    tokenInfoContainer:{
        width:"100%",
        flexDirection:"row",
        alignItems:"center"
    },
    tokenMsgContainer:{
        flexDirection:"row",
        alignItems:"center",
        flex:1,
        paddingTop:15,
        paddingBottom:15,
        borderBottomColor:"#eeeeee",
        borderBottomWidth:2/scale,
        marginLeft:10,
        // backgroundColor:"pink"
    },
    tokenInfoView:{
        flexDirection:"column",
        flex:1,

    },
    tokenName:{
        fontSize:fontSize_16
    },
    tokenAddress:{
        fontSize:fontSize_12,
        color:"#939393"
    }

})
export default L2_GetToken;


